﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Central_Control.Key
{
    /// <summary>
    /// Warning.xaml 的交互逻辑
    /// </summary>
    public partial class Warning : Window
    {
        bool isActivation;
        string localAppDataDirectory;
        string jsonFilePath;
        public static Warning instance { get; set; }
        public Warning()
        {
            InitializeComponent();
            instance = this;
            localAppDataDirectory=System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Central Control");
            jsonFilePath = System.IO.Path.Combine(localAppDataDirectory, "KeyFile.json");
        }


        // 加密
        static string Encrypt(string plainText)
        {
            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
            string encryptedText = Convert.ToBase64String(plainBytes);
            return encryptedText;
        }

        // 解密
        static string Decrypt(string encryptedText)
        {
            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
            string decryptedText = Encoding.UTF8.GetString(encryptedBytes);
            return decryptedText;
        }
        static string Decrypt(string cipherText, string key)
        {
            using (Aes aesAlg = Aes.Create())
            {
                byte[] keyBytes = Encoding.UTF8.GetBytes(key);
                Array.Resize(ref keyBytes, 32); // 32字节对应256位密钥
                aesAlg.Key = keyBytes;
                aesAlg.IV = new byte[16]; // 使用随机IV更安全，这里为演示简化

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            return srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
        }
        public void CheckData()
        {
            isActivation = false;
            // 读取 JSON 文件中的数据
            ExpirationData loadedData = ReadFromJsonFile(jsonFilePath);

            // 解密日期并输出
            if (DateTime.Now >= DateTime.Parse(Decrypt(loadedData.ExpirationDate)))
            {
                if(!this.IsVisible)
                this.ShowDialog();

            }
            else
            {
                DateTime targetTime = DateTime.Parse(Decrypt(loadedData.ExpirationDate));
                // 计算时间差
                TimeSpan timeDifference = targetTime.Subtract(DateTime.Now);

                MessageBox.Show($"剩余时间: {timeDifference:dd}天 {timeDifference:hh}小时 {timeDifference:mm}分钟{timeDifference:ss}秒", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        static ExpirationData ReadFromJsonFile(string filePath)
        {
            string jsonData = File.ReadAllText(filePath);
            return JsonConvert.DeserializeObject<ExpirationData>(jsonData);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            addKeys(KeyContent.Text);
        }
        public void addKeys(string key)
        {
            if (key != string.Empty)
            {
                try
                {
                    string Content = Decrypt(key.Trim(), "JSWH");

                    MessageBoxResult result = AddData(Content.Split('/')[1], key.Trim());
                    if (result == MessageBoxResult.OK)
                    {
                        // 用户点击了 "OK" 按钮，可以在这里执行关闭窗口的逻辑
                        KeyContent.Text = "";
                        this.Hide();  // 或者使用 this.Close();
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("激活码错误！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    KeyContent.Text = "";
                    return; // 或者执行其他错误处理逻辑
                }
            }
        }
        MessageBoxResult AddData(string Time,string Key)
        {
            isActivation = true;
            // 读取 JSON 文件中的数据
            ExpirationData loadedData = ReadFromJsonFile(jsonFilePath);
            if (Time == "1秒")
            {
                if(Key== loadedData.Key1)
                {
                    MessageBox.Show("激活码已失效!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return MessageBoxResult.No;
                }
                else
                {
                    DateTime dateTime = DateTime.Now.AddSeconds(1);
                    ExpirationData expirationData = new ExpirationData();
                    expirationData.ExpirationDate = Encrypt(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    expirationData.Key1 = Key;
                    // 将数据写入 JSON 文件
                    WriteToJsonFile(expirationData, jsonFilePath);

  


                    return MessageBox.Show("已激活1秒", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            else if (Time == "1分钟")
            {
                if (Key == loadedData.Key2)
                {
                    MessageBox.Show("激活码已失效!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return MessageBoxResult.No;
                }
                else
                {
                    DateTime dateTime = DateTime.Now.AddMinutes(1);
                    ExpirationData expirationData = new ExpirationData();
                    expirationData.ExpirationDate = Encrypt(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    expirationData.Key2 = Key;
                    // 将数据写入 JSON 文件
                    WriteToJsonFile(expirationData, jsonFilePath);
                    return MessageBox.Show("已激活1分钟", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }

            }
            else if (Time == "1天")
            {
                if (Key == loadedData.Key3)
                {
                    MessageBox.Show("激活码已失效!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return MessageBoxResult.No;
                }
                else
                {
                    DateTime dateTime = DateTime.Now.AddDays(1);
                    ExpirationData expirationData = new ExpirationData();
                    expirationData.ExpirationDate = Encrypt(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    expirationData.Key3 = Key;
                    // 将数据写入 JSON 文件
                    WriteToJsonFile(expirationData, jsonFilePath);
                    return MessageBox.Show("已激活1天", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                
            }
            else if (Time == "3天")
            {
                if (Key == loadedData.Key4)
                {
                    MessageBox.Show("激活码已失效!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return MessageBoxResult.No;
                }
                else
                {
                    DateTime dateTime = DateTime.Now.AddDays(3);
                    ExpirationData expirationData = new ExpirationData();
                    expirationData.ExpirationDate = Encrypt(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    expirationData.Key4 = Key; 
                    // 将数据写入 JSON 文件
                    WriteToJsonFile(expirationData, jsonFilePath);
                    return MessageBox.Show("已激活3天", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
               
            }
            else if (Time == "7天")
            {
                if (Key == loadedData.Key5)
                {
                    MessageBox.Show("激活码已失效!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return MessageBoxResult.No;
                }
                else
                {
                    DateTime dateTime = DateTime.Now.AddDays(7);
                    ExpirationData expirationData = new ExpirationData();
                    expirationData.ExpirationDate = Encrypt(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    expirationData.Key5 = Key;
                    // 将数据写入 JSON 文件
                    WriteToJsonFile(expirationData, jsonFilePath);
                    return MessageBox.Show("已激活7天", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
               
            }
            else if (Time == "14天")
            {
                if (Key == loadedData.Key6)
                {
                    MessageBox.Show("激活码已失效!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return MessageBoxResult.No;
                }
                else
                {
                    DateTime dateTime = DateTime.Now.AddDays(14);
                    ExpirationData expirationData = new ExpirationData();
                    expirationData.ExpirationDate = Encrypt(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    expirationData.Key6 = Key;
                    // 将数据写入 JSON 文件
                    WriteToJsonFile(expirationData, jsonFilePath);
                    return MessageBox.Show("已激活14天", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
               
            }
            else
            {
                if (Key == loadedData.Key7)
                {
                    MessageBox.Show("激活码已失效!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return MessageBoxResult.No;
                }
                else
                {
                    DateTime dateTime = DateTime.Now.AddDays(30);
                    ExpirationData expirationData = new ExpirationData();
                    expirationData.ExpirationDate = Encrypt(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    expirationData.Key7 = Key;
                    // 将数据写入 JSON 文件
                    WriteToJsonFile(expirationData, jsonFilePath);
                    return MessageBox.Show("已激活30天", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                
            }
        }
        void WriteToJsonFile(ExpirationData data, string filePath)
        {
            string jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
            File.WriteAllText(filePath, jsonData);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (isActivation)
            {
                e.Cancel = true;
                this.Hide();
            }
            else
            {
                Application.Current.Shutdown();
            }

        }

        public void CreatKeyJson()
        {


            // 创建包含指定内容的 JSON 对象
            var jsonObject = new
            {
                ExpirationDate = "MjAyNC0wMS0wNSAxMjowMjoyOQ==",
                key1="null",
                key2="null",   
                key3="null",
                key4="null",
                key5="null",
                key6="null",
                key7="null",
            };

            // 将 JSON 对象序列化为 JSON 字符串
            string jsonString = JsonConvert.SerializeObject(jsonObject);

            // 将 JSON 字符串写入文件
            File.WriteAllText(jsonFilePath, jsonString);

        }
    }
    public class ExpirationData
    {
        public string ExpirationDate;
        public string Key1;
        public string Key2;
        public string Key3;
        public string Key4;
        public string Key5;
        public string Key6;
        public string Key7;
    }
}

